package flc.ast.dialog;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.view.Gravity;
import android.view.View;

import androidx.annotation.NonNull;

import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.ToastUtils;

import flc.ast.R;
import flc.ast.databinding.DialogSaveStyleBinding;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.base.BaseSmartDialog;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.RxUtil;

public class SaveDialog extends BaseSmartDialog<DialogSaveStyleBinding> implements View.OnClickListener {
    public boolean isDraft;
    public Bitmap saveBitmap;

    public SaveDialog(@NonNull Context context) {
        super(context);
    }

    @Override
    protected int getGravity() {
        return Gravity.CENTER;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.dialog_save_style;
    }

    @Override
    protected void initView(View view) {
        mDataBinding.tvCancel.setOnClickListener(this);
        mDataBinding.tvSave.setOnClickListener(this);

        mDataBinding.ivImg.setImageBitmap(saveBitmap);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tvCancel:
                dismiss();
                break;
            case R.id.tvSave:
                dismiss();
                saveImg();
                break;
            default:
                break;
        }
    }

    //保存图片
    private void saveImg() {
        if (saveBitmap == null) return;
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RxUtil.create(new RxUtil.Callback<String>() {

                    @Override
                    public void doBackground(ObservableEmitter<String> emitter) {
                        if (isDraft) {
                            //保存到草稿箱
                            String filePath = FileUtil.generateFilePath(Content.myDrafts, ".png");
                            ImageUtils.save(saveBitmap, filePath, Bitmap.CompressFormat.PNG);
                        } else {
                            ImageUtils.save2Album(saveBitmap, Bitmap.CompressFormat.PNG);
                        }
                        emitter.onNext("");
                    }

                    @Override
                    public void accept(String path) {
                        if (listener != null) {
                            listener.clickSave();
                        }
                    }
                });
            }
        }, 1000);
    }

    private Ilistener listener;

    public void setListener(Ilistener listener) {
        this.listener = listener;
    }

    public interface Ilistener {
        void clickSave();
    }
}
